import { computed, ref, type Ref } from 'vue'
import { useQuery } from '@tanstack/vue-query'
import type { TableColumnData } from '@arco-design/web-vue'

import {
  ApiGetCourseExperiments,
  ApiSearchCourse,
  KeyApiGetCourseExperiments,
  KeyApiSearchCourse
} from '@/apis/course'

export function useCourseTable() {
  const columns = [
    {
      dataIndex: 'id',
      title: '课程ID',
      align: 'center',
      width: 80
    },
    {
      dataIndex: 'name',
      title: '课程名称'
    },
    {
      dataIndex: 'description',
      title: '课程简述',
      ellipsis: true,
      tooltip: { position: 'left' }
    },
    {
      align: 'center',
      title: '课程详情',
      slotName: 'course'
    }
  ] as const satisfies TableColumnData[]

  const { data: courses } = useQuery({
    queryKey: KeyApiSearchCourse,
    staleTime: 5 * 60_000,
    queryFn: () => ApiSearchCourse({}),
    select: ({ data }) => data
  })

  return { columns, courses }
}

export function useExperimentList(showList: () => void) {
  const courseID = ref<number>(0)
  const courseName = ref<string>('')
  const toggleCourse = (id: number, name: string) => {
    courseID.value = id
    courseName.value = name
    showList()
  }

  const { data: experiments, isFetching } = useQuery({
    enabled: computed(() => courseID.value !== 0),
    queryKey: computed(() => KeyApiGetCourseExperiments(courseID.value)) as Ref<
      ReturnType<typeof KeyApiGetCourseExperiments>
    >,
    staleTime: 1000 * 60 * 5,
    queryFn: ({ queryKey: [, , id] }) => ApiGetCourseExperiments(id),
    select: ({ data }) => data
  })

  return {
    courseName,
    experiments,
    isFetching,
    toggleCourse
  }
}
